<template>
  <div class="thematic-map-container" :class="{ 'screenshot-mode': isScreenshotMode }">
    <!-- 使用Grid布局的地图区域 -->
    <div class="map-grid-container">
      <!-- 顶部地图标题区域 -->
      <div class="map-title-area">
        <div class="map-title-wrapper">
          <input 
            v-if="isEditingTitle"
            v-model="mapTitle"
            @blur="finishEditTitle"
            @keyup.enter="finishEditTitle"
            @keyup.esc="cancelEditTitle"
            class="map-title-input"
            ref="titleInput"
            placeholder="请输入地图标题"
          />
          <h2 
            v-else
            @dblclick="startEditTitle"
            class="map-title"
            :class="{ 'editable': !isScreenshotMode }"
          >
            {{ mapTitle || '地图标题' }}
          </h2>
        </div>
      </div>
      
      <!-- 左侧纬度标尺 -->
      <div class="latitude-ruler left-ruler">
        <div 
          v-for="lat in latitudeMarkers" 
          :key="`left-${lat.value}`" 
          class="ruler-mark latitude-mark"
          :style="{ top: lat.position + '%' }"
        >
          <span class="ruler-label">{{ lat.label }}</span>
        </div>
      </div>
      
      <!-- 地图主体 -->
      <div id="map" ref="mapContainer" class="map-main"></div>
      
      <!-- 右侧图例区域 -->
      <div class="map-legend-area">
        <div class="legend-container">
          <!-- 色带图例 - 只显示一种速度场或标量场 -->
          <ColorLegend
            v-if="currentLegend"
            :visible="true"
            :type="currentLegend.type"
            :min-value="currentLegend.minValue"
            :max-value="currentLegend.maxValue"
            :unit="currentLegend.unit"
            :color-config="currentLegend.colorConfig"
            :position="{ x: 0, y: 0 }"
            @close="closeLegend(currentLegendType)"
            class="full-height-legend"
          />
        </div>
        <!-- 图例标题区域 -->
        <div class="legend-title-area" v-if="currentLegend">
          <div class="legend-title-wrapper">
            <input 
              v-if="isEditingLegendTitle"
              v-model="legendTitle"
              @blur="finishEditLegendTitle"
              @keyup.enter="finishEditLegendTitle"
              @keyup.esc="cancelEditLegendTitle"
              class="legend-title-input"
              ref="legendTitleInput"
              placeholder="请输入图例标题"
            />
            <span 
              v-else
              @dblclick="startEditLegendTitle"
              class="legend-title"
              :class="{ 'editable': !isScreenshotMode }"
            >
              {{ legendTitle || getLegendDefaultTitle() }}
            </span>
          </div>
        </div>
      </div>
      
      <!-- 底部经度标尺 -->
      <div class="longitude-ruler bottom-ruler">
        <div 
          v-for="lng in longitudeMarkers" 
          :key="`bottom-${lng.value}`" 
          class="ruler-mark longitude-mark"
          :style="{ left: lng.position + '%' }"
        >
          <span class="ruler-label">{{ lng.label }}</span>
        </div>
      </div>
    </div>

    <!-- 地图内部组件容器 -->
    <div class="map-controls-container">
      <!-- 指北针 -->
      <div v-if="config.showNorthArrow !== false" class="map-north-arrow" ref="northArrowEl">
        <svg width="48" height="48" viewBox="0 0 100 100">
          <path d="M 50 0 L 65 50 L 50 100 L 35 50 Z" style="fill:#444;stroke:#fff;stroke-width:4" />
          <path d="M 50 0 L 65 50 L 50 20 Z" style="fill:#fff" />
          <text x="43" y="80" font-size="24" fill="#fff" style="font-weight:bold;">N</text>
        </svg>
      </div>

      <!-- 图例组件 -->
      <div v-if="config.showLegend && legend" class="map-legend" ref="legendEl">
        <h4>{{ legend.title }}</h4>
        <div class="legend-items">
          <div v-for="item in legend.items" :key="item.label" class="legend-item">
            <div class="legend-color" :style="{ backgroundColor: item.color, opacity: config.opacity }"></div>
            <span class="legend-label">{{ item.label }}</span>
          </div>
        </div>
      </div>

      <!-- 比例尺 -->
      <div v-if="config.showScale" class="map-scale" ref="scaleEl">
        比例尺: {{ currentScale }}
      </div>

      <!-- 统计图表面板 -->
      <div v-if="showChart" class="chart-panel">
        <div class="chart-header">
          <h4>{{ chartTitle }}</h4>
          <button @click="toggleChart" class="close-btn">×</button>
        </div>
        <div id="stats-chart" ref="chartContainer"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import * as echarts from 'echarts';
import { sampleData, mapConfigs } from '@/data/sampleData.js';
import { initMap } from '@/module/Class_Map.js';
import Config from '@/module/Class_Map.js';
import ColorLegend from '@/components/ColorLegend.vue';

const props = defineProps({
  config: {
    type: Object,
    default: () => ({})
  }
});

const mapContainer = ref(null);
const chartContainer = ref(null);
const northArrowEl = ref(null);
const legendEl = ref(null);
const scaleEl = ref(null);
const titleInput = ref(null);
const map = ref(null);
const chart = ref(null);
const featureLayer = ref(null);
const showChart = ref(false);
const chartTitle = ref('');
const legend = ref(null);
const geoJsonData = ref(null);
const currentScale = ref('1:5,000,000'); // 动态比例尺
const longitudeMarkers = ref([]); // 经度标尺标记
const latitudeMarkers = ref([]); // 纬度标尺标记
const activeLegends = ref({}); // 活动图例信息
const mapTitle = ref('地图标题'); // 地图标题
const isEditingTitle = ref(false); // 是否正在编辑标题
const originalTitle = ref(''); // 编辑前的原始标题
const isScreenshotMode = ref(false); // 截图模式
const legendTitle = ref(''); // 图例标题
const isEditingLegendTitle = ref(false); // 是否正在编辑图例标题
const legendTitleInput = ref(null); // 图例标题输入框
const originalLegendTitle = ref(''); // 编辑前的原始图例标题
let geoJsonLayer = null;

// 过滤后的图例 - 只显示速度场和标量场
const filteredLegends = computed(() => {
  const allowedTypes = ['wind_speed', 'current_speed', 'seatemp_scalar'];
  const filtered = {};
  
  for (const [layerType, legendInfo] of Object.entries(activeLegends.value)) {
    if (allowedTypes.includes(layerType)) {
      filtered[layerType] = legendInfo;
    }
  }
  
  return filtered;
});

// 当前显示的图例 - 只显示一个
const currentLegend = computed(() => {
  const allowedTypes = ['wind_speed', 'current_speed', 'seatemp_scalar'];
  
  // 按优先级顺序查找第一个可用的图例
  for (const layerType of allowedTypes) {
    if (activeLegends.value[layerType]) {
      return activeLegends.value[layerType];
    }
  }
  
  return null;
});

// 当前图例类型
const currentLegendType = computed(() => {
  const allowedTypes = ['wind_speed', 'current_speed', 'seatemp_scalar'];
  
  for (const layerType of allowedTypes) {
    if (activeLegends.value[layerType]) {
      return layerType;
    }
  }
  
  return null;
});

let gridLayer = null;

const makeDraggable = (element) => {
  if (!element) return;
  element.style.cursor = 'move';

  const onMouseDown = (e) => {
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.tagName === 'SELECT') {
      return;
    }

    const parent = element.parentElement;
    if (!parent) return;

    const parentRect = parent.getBoundingClientRect();
    const elementRect = element.getBoundingClientRect();

    const offsetX = e.clientX - elementRect.left;
    const offsetY = e.clientY - elementRect.top;

    const onMouseMove = (moveEvent) => {
      moveEvent.preventDefault();

      let newX = moveEvent.clientX - offsetX - parentRect.left;
      let newY = moveEvent.clientY - offsetY - parentRect.top;

      newX = Math.max(0, Math.min(newX, parentRect.width - elementRect.width));
      newY = Math.max(0, Math.min(newY, parentRect.height - elementRect.height));

      element.style.left = `${newX}px`;
      element.style.top = `${newY}px`;
      element.style.right = 'auto';
      element.style.bottom = 'auto';
    };

    const onMouseUp = () => {
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    };

    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
  };

  element.addEventListener('mousedown', onMouseDown);
};

watch(northArrowEl, (el) => el && makeDraggable(el));
watch(legendEl, (el) => el && makeDraggable(el));
watch(scaleEl, (el) => el && makeDraggable(el));

onMounted(() => {
  nextTick(() => {
    initMap();
    // 绑定事件，保证经纬度标尺随地图交互刷新
    const map = Config.mapObj.map;
    if (map) {
      map.on('zoomend', updateCoordinateRulers);
      map.on('moveend', updateCoordinateRulers);
      map.on('zoom', updateCoordinateRulers);
      map.on('drag', () => {
        if (!window.dragUpdateTimeout) {
          window.dragUpdateTimeout = setTimeout(() => {
            updateCoordinateRulers();
            window.dragUpdateTimeout = null;
          }, 100);
        }
      });
      // 初始化后主动刷新一次
      updateCoordinateRulers();
    }
    
    // 监听图例变化（如果有全局的图层管理器）
    if (window.globalLayerManager) {
      console.log('添加图例监听器');
      window.globalLayerManager.addLegendChangeListener(handleLegendChange);
      
      // 立即同步一次当前图例状态
      if (Object.keys(window.globalLayerManager.activeLegends).length > 0) {
        console.log('立即同步图例状态:', window.globalLayerManager.activeLegends);
        activeLegends.value = { ...window.globalLayerManager.activeLegends };
      }
    } else {
      console.warn('window.globalLayerManager 未找到');
    }
  });
});

// 监听配置变化
watch(() => props.config, (newConfig) => {
  if (newConfig) {
    nextTick(() => {
      updateMapDisplay(newConfig);
    });
  }
}, { deep: true });

// 监听当前图例变化，重置标题
watch(currentLegend, (newLegend) => {
  if (newLegend) {
    // 当图例改变时，重置为默认标题
    legendTitle.value = '';
  }
});

// 图例变化处理函数
const handleLegendChange = (legends) => {
  console.log('图例数据变化:', legends);
  activeLegends.value = { ...legends };
};

// 获取图例位置 - 使用CSS定位到地图左下角
const getLegendPosition = (layerType) => {
  const spacing = 80; // 多个图例之间的间距
  const baseX = 20; // 基础左边距（相对于地图主体）
  
  const layerOrder = ['wind_speed', 'current_speed', 'seatemp_scalar'];
  const index = layerOrder.indexOf(layerType);
  
  return {
    x: baseX + (index >= 0 ? index * spacing : 0),
    bottom: 20 // 距离底部的距离
  };
};

// 获取侧边栏图例位置
const getLegendPositionInSidebar = (layerType) => {
  const spacing = 120; // 多个图例之间的间距（垂直）
  const baseY = 20; // 基础顶部边距
  
  const layerOrder = ['wind_speed', 'current_speed', 'seatemp_scalar'];
  const index = layerOrder.indexOf(layerType);
  
  return {
    x: 10, // 距离侧边栏左边距
    y: baseY + (index >= 0 ? index * spacing : 0) // 垂直排列
  };
};

// 开始编辑标题
const startEditTitle = () => {
  if (isScreenshotMode.value) return;
  originalTitle.value = mapTitle.value;
  isEditingTitle.value = true;
  nextTick(() => {
    if (titleInput.value) {
      titleInput.value.focus();
      titleInput.value.select();
    }
  });
};

// 完成编辑标题
const finishEditTitle = () => {
  isEditingTitle.value = false;
  if (!mapTitle.value.trim()) {
    mapTitle.value = originalTitle.value || '地图标题';
  }
};

// 取消编辑标题
const cancelEditTitle = () => {
  mapTitle.value = originalTitle.value;
  isEditingTitle.value = false;
};

// 关闭图例
const closeLegend = (layerType) => {
  if (window.globalLayerManager && layerType) {
    window.globalLayerManager.removeLegend(layerType);
  }
};

const loadGeoJson = async () => {
  try {
    const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json');
    if (!response.ok) {
      throw new Error('网络响应失败');
    }
    geoJsonData.value = await response.json();

    if (map.value) {
      // 默认显示边界
      geoJsonLayer = L.geoJSON(geoJsonData.value, {
        style: {
          color: "#999",
          weight: 1,
          fillOpacity: 0
        }
      }).addTo(map.value);
      map.value.fitBounds(geoJsonLayer.getBounds());
      
      // 地图数据加载完成后更新坐标标尺
      setTimeout(() => {
        updateCoordinateRulers();
      }, 200);
    }
  } catch (error) {
    console.error('加载GeoJSON数据时出错:', error);
  }
};

// 计算动态比例尺
const updateScale = () => {
  if (!map.value) return;

  const zoom = map.value.getZoom();
  const center = map.value.getCenter();

  // 根据缩放级别计算比例尺
  // 使用Web墨卡托投影的公式计算比例尺
  const scale = calculateScaleFromZoom(zoom, center.lat);
  currentScale.value = formatScale(scale);
};

// 根据缩放级别和纬度计算比例尺
const calculateScaleFromZoom = (zoom, lat) => {
  // Web墨卡托投影的比例尺计算公式
  // 在赤道处，1像素 = 156543.03392 / 2^zoom 米
  const metersPerPixel = 156543.03392 / Math.pow(2, zoom);

  // 考虑纬度的影响（墨卡托投影在极地变形）
  const latRad = lat * Math.PI / 180;
  const metersPerPixelAtLat = metersPerPixel * Math.cos(latRad);

  // 假设屏幕DPI为96，1英寸 = 25.4毫米
  const dpi = 96;
  const metersPerInch = 0.0254;
  const metersPerPixelAtDPI = metersPerInch / dpi;

  // 计算比例尺分母
  const scaleDenominator = metersPerPixelAtLat / metersPerPixelAtDPI;

  // 返回最接近的标准比例尺
  return getNearestStandardScale(scaleDenominator);
};

// 更新经纬度标尺
const updateCoordinateRulers = () => {
  const realMap = Config.mapObj.map;
  if (!realMap) return;

  try {
    const bounds = realMap.getBounds();
    const zoom = realMap.getZoom();
    
    // console.log('更新经纬度标尺 - zoom:', zoom);
    // console.log('bounds - 西:', bounds.getWest(), '东:', bounds.getEast(), '南:', bounds.getSouth(), '北:', bounds.getNorth());
    
    // 检查bounds是否有效
    if (!bounds || !bounds.isValid()) {
      console.warn('地图bounds无效');
      return;
    }
  
    // 根据缩放层级确定标尺间距
    let lngStep, latStep;
    
    if (zoom <= 3) {
      lngStep = 30;
      latStep = 20;
    } else if (zoom <= 5) {
      lngStep = 15;
      latStep = 10;
    } else if (zoom <= 7) {
      lngStep = 10;
      latStep = 5;
    } else if (zoom <= 9) {
      lngStep = 5;
      latStep = 2;
    } else if (zoom <= 11) {
      lngStep = 2;
      latStep = 1;
    } else if (zoom <= 13) {
      lngStep = 1;
      latStep = 0.5;
    } else {
      lngStep = 0.5;
      latStep = 0.25;
    }

    // 计算经度标记 - 使用Leaflet的投影方法获取更精确的位置
    const west = bounds.getWest();
    const east = bounds.getEast();
    const westRounded = Math.floor(west / lngStep) * lngStep;
    const eastRounded = Math.ceil(east / lngStep) * lngStep;
    
    // console.log('经度计算:', { west, east, westRounded, eastRounded, lngStep });
    
    longitudeMarkers.value = [];
    for (let lng = westRounded; lng <= eastRounded; lng += lngStep) {
      if (lng >= west && lng <= east) {
        try {
          const mapContainer = realMap.getContainer();
          const mapWidth = mapContainer.offsetWidth;
          
          // 获取经度在地图容器中的像素位置
          const point = realMap.latLngToContainerPoint([(bounds.getSouth() + bounds.getNorth()) / 2, lng]);
          const pixelPosition = point.x;
          
          // 转换为百分比位置
          const position = (pixelPosition / mapWidth) * 100;
          
          const marker = {
            value: lng,
            position: Math.max(0, Math.min(100, position)), // 确保在0-100%范围内
            label: formatCoordinate(lng, 'lng')
          };
          longitudeMarkers.value.push(marker);
          // console.log('添加经度标记:', { lng, pixelPos: pixelPosition, position: position.toFixed(1) + '%', label: marker.label });
        } catch (error) {
          // 如果Leaflet方法失败，回退到原始计算方式
          const position = ((lng - west) / (east - west)) * 100;
          const marker = {
            value: lng,
            position: position,
            label: formatCoordinate(lng, 'lng')
          };
          longitudeMarkers.value.push(marker);
          // console.log('回退经度标记:', { lng, position: position.toFixed(1) + '%', label: marker.label });
        }
      }
    }

    // 计算纬度标记 - 使用Leaflet的投影方法获取更精确的位置
    const south = bounds.getSouth();
    const north = bounds.getNorth();
    const southRounded = Math.floor(south / latStep) * latStep;
    const northRounded = Math.ceil(north / latStep) * latStep;
    
    // console.log('纬度计算:', { south, north, southRounded, northRounded, latStep });
    
    latitudeMarkers.value = [];
    for (let lat = southRounded; lat <= northRounded; lat += latStep) {
      if (lat >= south && lat <= north) {
        try {
          const mapContainer = realMap.getContainer();
          const mapHeight = mapContainer.offsetHeight;
          
          // 获取纬度在地图容器中的像素位置
          const point = realMap.latLngToContainerPoint([lat, (bounds.getWest() + bounds.getEast()) / 2]);
          const pixelPosition = point.y;
          
          // 转换为百分比位置
          const position = (pixelPosition / mapHeight) * 100;
          
          const marker = {
            value: lat,
            position: Math.max(0, Math.min(100, position)), // 确保在0-100%范围内
            label: formatCoordinate(lat, 'lat')
          };
          latitudeMarkers.value.push(marker);
          // console.log('添加纬度标记:', { lat, pixelPos: pixelPosition, position: position.toFixed(1) + '%', label: marker.label });
        } catch (error) {
          // 如果Leaflet方法失败，回退到原始计算方式
          const position = ((north - lat) / (north - south)) * 100;
          const marker = {
            value: lat,
            position: position,
            label: formatCoordinate(lat, 'lat')
          };
          latitudeMarkers.value.push(marker);
                      // console.log('回退纬度标记:', { lat, position: position.toFixed(1) + '%', label: marker.label });
        }
      }
    }
    
    // console.log('经纬度标尺计算完成:');
    // console.log('- 经度标记数量:', longitudeMarkers.value.length);
    // console.log('- 纬度标记数量:', latitudeMarkers.value.length);
    
  } catch (error) {
    console.warn('更新经纬度标尺时出错:', error);
    longitudeMarkers.value = [];
    latitudeMarkers.value = [];
  }
};

// 格式化坐标显示
const formatCoordinate = (value, type) => {
  const absValue = Math.abs(value);
  const direction = type === 'lng' 
    ? (value >= 0 ? 'E' : 'W')
    : (value >= 0 ? 'N' : 'S');
  
  // 根据数值大小决定显示精度
  if (absValue >= 1) {
    return `${absValue.toFixed(0)}°${direction}`;
  } else {
    return `${absValue.toFixed(1)}°${direction}`;
  }
};

// 获取最接近的标准比例尺
const getNearestStandardScale = (scale) => {
  const standardScales = [
    1000, 2000, 5000, 10000, 20000, 25000, 50000, 100000, 200000, 250000,
    500000, 1000000, 2000000, 5000000, 10000000, 20000000, 50000000, 100000000
  ];

  let nearest = standardScales[0];
  let minDiff = Math.abs(scale - nearest);

  for (const standardScale of standardScales) {
    const diff = Math.abs(scale - standardScale);
    if (diff < minDiff) {
      minDiff = diff;
      nearest = standardScale;
    }
  }

  return nearest;
};

const updateMapDisplay = (config) => {
  if (!map.value) return;

  // 在更新前关闭所有弹窗，防止状态问题
  map.value.closePopup();

  // 彻底清除并重建特征图层，以解决标签和弹窗的状态残留问题
  if (featureLayer.value) {
    map.value.removeLayer(featureLayer.value);
  }
  featureLayer.value = L.featureGroup().addTo(map.value);

  if (gridLayer) {
    map.value.removeLayer(gridLayer);
    gridLayer = null;
  }
  // 隐藏默认边界图层，如果专题图是面状图
  if (geoJsonLayer) {
    if (config.thematicType === 'choropleth') {
      geoJsonLayer.setStyle({ fillOpacity: 0, "color": "transparent" });
    } else {
      geoJsonLayer.setStyle({ fillOpacity: 0, "color": "#999" });
    }
  }

  // 根据配置显示或隐藏经纬网
  if (config.showGrid) {
    showGrid();
  } else {
    // 隐藏经纬网
    if (gridLayer) {
      map.value.removeLayer(gridLayer);
      gridLayer = null;
    }
  }

  // 始终更新坐标标尺
  updateCoordinateRulers();

  // 获取数据并显示专题图
  const data = sampleData[config.dataSource];
  if (data) {
    displayThematicMap(data, config);
  }
};

const displayThematicMap = (data, config) => {
  const colorScheme = mapConfigs.colorSchemes.find(s => s.value === config.colorScheme);
  const colors = colorScheme ? colorScheme.colors : mapConfigs.colorSchemes[0].colors;

  switch (config.thematicType) {
    case 'point':
      displayPointMap(data, colors, config);
      break;
    case 'choropleth':
      displayChoroplethMap(data, colors, config);
      break;
    case 'heatmap':
      displayHeatMap(data, colors, config);
      break;
    case 'flow':
      displayFlowMap(data, colors, config);
      break;
    case '3dbar':
      display3DBarMap(data, colors, config);
      break;
    default:
      displayPointMap(data, colors, config);
  }

  // 创建图例
  createLegend(config, colors, data);
};

const displayPointMap = (data, colors, config) => {
  if (!data || data.length === 0) return;

  const valueField = getValueField(config.dataSource);
  const values = data.map(item => item[valueField]).filter(v => v != null);
  const minValue = Math.min(...values);
  const maxValue = Math.max(...values);

  data.forEach(item => {
    if (item.lat && item.lng && item[valueField] != null) {
      const value = item[valueField];
      const ratio = (value - minValue) / (maxValue - minValue);
      const colorIndex = Math.min(Math.floor(ratio * colors.length), colors.length - 1);
      const radius = 5 + (ratio * 20); // 5-25px 半径

      const circle = L.circleMarker([item.lat, item.lng], {
        radius: radius,
        fillColor: colors[colorIndex],
        color: colors[colorIndex],
        weight: 2,
        opacity: config.opacity,
        fillOpacity: config.opacity * 0.8
      }).addTo(featureLayer.value);

      // 添加弹窗
      let popupContent = `<strong>${item.name}</strong><br>`;
      popupContent += `${getValueLabel(config.dataSource)}: ${formatValue(value, config.dataSource)}`;

      if (config.showLabels) {
        circle.bindTooltip(item.name, {
          permanent: true,
          direction: 'top',
          className: 'map-label'
        });
      }

      circle.bindPopup(popupContent, { autoPan: false });
    }
  });

  // 调整地图视图以包含所有点
  const bounds = featureLayer.value.getBounds();
  if (bounds.isValid()) {
    map.value.fitBounds(bounds, { padding: [20, 20] });
  }
};

const displayHeatMap = (data, colors, config) => {
  // 创建热力图效果（使用多个半透明圆圈）
  if (!data || data.length === 0) return;

  const valueField = getValueField(config.dataSource);
  const values = data.map(item => item[valueField]).filter(v => v != null);
  const minValue = Math.min(...values);
  const maxValue = Math.max(...values);

  data.forEach(item => {
    if (item.lat && item.lng && item[valueField] != null) {
      const value = item[valueField];
      const ratio = (value - minValue) / (maxValue - minValue);
      const colorIndex = Math.min(Math.floor(ratio * colors.length), colors.length - 1);
      const radius = 20 + (ratio * 50); // 更大的半径用于热力效果

      // 创建多层圆圈实现热力效果
      for (let i = 0; i < 3; i++) {
        const circle = L.circle([item.lat, item.lng], {
          radius: (radius - i * 5) * 1000, // 转换为米
          fillColor: colors[colorIndex],
          color: 'transparent',
          fillOpacity: config.opacity * 0.2 / (i + 1)
        }).addTo(featureLayer.value);
      }

      // 中心点标记
      const marker = L.circleMarker([item.lat, item.lng], {
        radius: 3,
        fillColor: colors[colorIndex],
        color: 'white',
        weight: 1,
        opacity: 1,
        fillOpacity: 1
      }).addTo(featureLayer.value);

      let popupContent = `<strong>${item.name}</strong><br>`;
      popupContent += `${getValueLabel(config.dataSource)}: ${formatValue(value, config.dataSource)}`;
      marker.bindPopup(popupContent, { autoPan: false });
    }
  });

  const bounds = featureLayer.value.getBounds();
  if (bounds.isValid()) {
    map.value.fitBounds(bounds, { padding: [50, 50] });
  }
};

const displayChoroplethMap = (data, colors, config) => {
  if (!geoJsonData.value) {
    console.warn('GeoJSON数据尚未加载，回退到点图模式。');
    displayPointMap(data, colors, config);
    return;
  }

  const valueField = getValueField(config.dataSource);
  // 创建一个名称到值的映射，处理名称不完全匹配的情况
  const dataMap = new Map();
  data.forEach(item => {
    // 简化省份名称以提高匹配率，例如 "北京市" -> "北京"
    const simpleName = item.name.replace(/省|市|自治区|壮族|回族|维吾尔/g, '');
    dataMap.set(simpleName, item[valueField]);
  });

  const values = data.map(item => item[valueField]).filter(v => v != null);
  if (values.length === 0) return;

  const minValue = Math.min(...values);
  const maxValue = Math.max(...values);

  L.geoJSON(geoJsonData.value, {
    style: (feature) => {
      const featureName = feature.properties.name.replace(/省|市|自治区|壮族|回族|维吾尔/g, '');
      const value = dataMap.get(featureName);
      let fillColor = '#E0E0E0'; // 无数据时的默认颜色

      if (value != null) {
        const ratio = (maxValue - minValue === 0) ? 0.5 : (value - minValue) / (maxValue - minValue);
        const colorIndex = Math.min(Math.floor(ratio * colors.length), colors.length - 1);
        fillColor = colors[colorIndex];
      }
      return {
        color: '#FFFFFF',
        weight: 1,
        opacity: 1,
        fillColor: fillColor,
        fillOpacity: config.opacity
      };
    },
    onEachFeature: (feature, layer) => {
      const featureName = feature.properties.name.replace(/省|市|自治区|壮族|回族|维吾尔/g, '');
      const value = dataMap.get(featureName);

      if (value != null) {
        let popupContent = `<strong>${feature.properties.name}</strong><br>`;
        popupContent += `${getValueLabel(config.dataSource)}: ${formatValue(value, config.dataSource)}`;
        layer.bindPopup(popupContent, { autoPan: false });
      } else {
        layer.bindPopup(`<strong>${feature.properties.name}</strong><br>暂无数据`, { autoPan: false });
      }
    }
  }).addTo(featureLayer.value);

  if (featureLayer.value.getBounds().isValid()) {
    map.value.fitBounds(featureLayer.value.getBounds());
  }
};

const displayFlowMap = (data, colors, config) => {
  if (config.dataSource === 'trafficFlow') {
    data.forEach((flow, index) => {
      const colorIndex = index % colors.length;
      const coordinates = flow.coordinates.map(coord => [coord[0], coord[1]]);

      const line = L.polyline(coordinates, {
        color: colors[colorIndex],
        weight: Math.max(2, (flow.flow / flow.capacity) * 10),
        opacity: config.opacity
      }).addTo(featureLayer.value);

      // 添加箭头效果
      const arrowHead = L.polylineDecorator(line, {
        patterns: [{
          offset: '50%',
          repeat: 0,
          symbol: L.Symbol.arrowHead({
            pixelSize: 15,
            pathOptions: {
              fillOpacity: config.opacity,
              weight: 0,
              color: colors[colorIndex]
            }
          })
        }]
      });

      if (L.polylineDecorator) {
        arrowHead.addTo(featureLayer.value);
      }

      let popupContent = `<strong>${flow.name}</strong><br>`;
      popupContent += `当前流量: ${flow.flow}<br>`;
      popupContent += `最大容量: ${flow.capacity}<br>`;
      popupContent += `拥堵度: ${Math.round((flow.flow / flow.capacity) * 100)}%`;
      line.bindPopup(popupContent, { autoPan: false });
    });
  } else {
    // 对于其他数据源，显示点符号图
    displayPointMap(data, colors, config);
  }
};

const display3DBarMap = (data, colors, config) => {
  // 使用ECharts创建3D柱状图叠加到地图上
  showChart.value = true;
  chartTitle.value = `${getDataSourceLabel(config.dataSource)} - 3D柱状图`;

  nextTick(() => {
    if (chartContainer.value) {
      if (!chart.value) {
        chart.value = echarts.init(chartContainer.value);
      }

      const valueField = getValueField(config.dataSource);
      const chartData = data.map(item => ({
        name: item.name,
        value: item[valueField]
      })).sort((a, b) => b.value - a.value);

      const option = {
        title: {
          text: chartTitle.value,
          textStyle: { fontSize: 14 }
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const data = params[0];
            return `${data.name}<br>${getValueLabel(config.dataSource)}: ${formatValue(data.value, config.dataSource)}`;
          }
        },
        xAxis: {
          type: 'category',
          data: chartData.map(item => item.name),
          axisLabel: {
            rotate: 45,
            fontSize: 10
          }
        },
        yAxis: {
          type: 'value',
          name: getValueLabel(config.dataSource)
        },
        series: [{
          data: chartData.map((item, index) => ({
            value: item.value,
            itemStyle: {
              color: colors[index % colors.length]
            }
          })),
          type: 'bar',
          label: {
            show: true,
            position: 'top',
            fontSize: 10,
            formatter: (params) => formatValue(params.value, config.dataSource)
          }
        }]
      };

      chart.value.setOption(option);
    }
  });

  // 同时在地图上显示点
  displayPointMap(data, colors, config);
};

const createLegend = (config, colors, data) => {
  const valueField = getValueField(config.dataSource);
  const values = data.map(item => item[valueField]).filter(v => v != null);

  if (values.length === 0) return;

  const minValue = Math.min(...values);
  const maxValue = Math.max(...values);
  const range = maxValue - minValue;

  legend.value = {
    title: getValueLabel(config.dataSource),
    items: colors.map((color, index) => {
      const value = minValue + (range * index / (colors.length - 1));
      return {
        color: color,
        label: formatValue(value, config.dataSource)
      };
    })
  };
};

const toggleChart = () => {
  showChart.value = !showChart.value;
};

// 辅助函数
const getValueField = (dataSource) => {
  const fieldMap = {
    cityPopulation: 'population',
    provinceGDP: 'gdp',
    airQuality: 'aqi',
    temperatureData: 'temp',
    trafficFlow: 'flow'
  };
  return fieldMap[dataSource] || 'value';
};

const getValueLabel = (dataSource) => {
  const labelMap = {
    cityPopulation: '人口(万人)',
    provinceGDP: 'GDP(亿元)',
    airQuality: 'AQI指数',
    temperatureData: '温度(°C)',
    trafficFlow: '流量'
  };
  return labelMap[dataSource] || '数值';
};

const getDataSourceLabel = (dataSource) => {
  const labelMap = {
    cityPopulation: '城市人口',
    provinceGDP: '省份GDP',
    airQuality: '空气质量',
    temperatureData: '温度分布',
    trafficFlow: '交通流量'
  };
  return labelMap[dataSource] || '数据';
};

const formatValue = (value, dataSource) => {
  if (value == null) return '-';

  switch (dataSource) {
    case 'cityPopulation':
      return `${value}万人`;
    case 'provinceGDP':
      return `${value}亿元`;
    case 'airQuality':
      return `${value}`;
    case 'temperatureData':
      return `${value}°C`;
    case 'trafficFlow':
      return `${value}辆/小时`;
    default:
      return `${value}`;
  }
};

const formatScale = (scale) => {
  return `1:${scale.toLocaleString()}`;
};

// 开始编辑图例标题
const startEditLegendTitle = () => {
  if (isScreenshotMode.value) return;
  originalLegendTitle.value = legendTitle.value;
  isEditingLegendTitle.value = true;
  nextTick(() => {
    if (legendTitleInput.value) {
      legendTitleInput.value.focus();
      legendTitleInput.value.select();
    }
  });
};

// 完成编辑图例标题
const finishEditLegendTitle = () => {
  isEditingLegendTitle.value = false;
  if (!legendTitle.value.trim()) {
    legendTitle.value = '';
  }
};

// 取消编辑图例标题
const cancelEditLegendTitle = () => {
  legendTitle.value = originalLegendTitle.value;
  isEditingLegendTitle.value = false;
};

// 获取图例默认标题
const getLegendDefaultTitle = () => {
  if (!currentLegend.value) return '图例标题';
  
  // 根据当前图例类型（layerType）返回对应的中文名称
  const typeNameMap = {
    'wind_speed': '风速（m/s）',
    'current_speed': '流速（m/s）',
    'seatemp_scalar': '海温（℃）',
    'wave_height': '浪高（m）',
    'wave_direction': '浪向',
    'wave_period': '浪周期'
  };
  
  // 使用 currentLegendType 而不是 currentLegend.value.type
  const layerType = currentLegendType.value;
  console.log('当前图层类型:', layerType);
  console.log('当前图例数据:', currentLegend.value);
  
  const typeName = typeNameMap[layerType] || layerType || '图例';
  console.log('图例名称:', typeName);
  
  return typeName;
};

// 暴露方法供父组件调用
defineExpose({
  clearMap: () => {
    if (featureLayer.value) {
      featureLayer.value.clearLayers();
    }
    // 清除经纬网
    if (gridLayer) {
      map.value.removeLayer(gridLayer);
      gridLayer = null;
    }
    // 清除坐标标尺
    longitudeMarkers.value = [];
    latitudeMarkers.value = [];
    showChart.value = false;
    legend.value = null;
  },
  updateDisplay: updateMapDisplay,
  // 添加单独的图层控制方法
  addWindLayer: (config, options) => addWindLayer(config, options),
  addWaveLayer: (config, options) => addWaveLayer(config, options),
  addCurrentLayer: (config, options) => addCurrentLayer(config, options),
  removeWindLayer: () => {
    console.log('风场图层已清除');
  },
  removeWaveLayer: () => {
    console.log('海浪图层已清除');
  },
  removeCurrentLayer: () => {
    console.log('海流图层已清除');
  }
});
</script>

<style scoped>
.thematic-map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

/* 截图模式样式 */
.thematic-map-container.screenshot-mode {
  background: #ffffff !important;
  position: relative !important;
  width: 100% !important;
  height: 100% !important;
  overflow: visible !important;
}

.thematic-map-container.screenshot-mode .map-grid-container {
  position: relative !important;
  width: 100% !important;
  height: 100% !important;
}

.thematic-map-container.screenshot-mode .map-title-area {
  position: relative !important;
}

.thematic-map-container.screenshot-mode .map-main {
  position: relative !important;
  width: 100% !important;
  height: 100% !important;
}

.thematic-map-container.screenshot-mode .map-legend-area {
  position: relative !important;
}

.thematic-map-container.screenshot-mode .map-controls-container {
  pointer-events: none;
  position: absolute !important;
  top: 60px !important;
  left: 40px !important;
  right: 120px !important;
  bottom: 30px !important;
  z-index: 1000 !important;
}

.thematic-map-container.screenshot-mode .map-north-arrow,
.thematic-map-container.screenshot-mode .map-legend,
.thematic-map-container.screenshot-mode .map-scale,
.thematic-map-container.screenshot-mode .save-image-btn,
.thematic-map-container.screenshot-mode .chart-panel {
  pointer-events: auto;
  position: absolute !important;
  z-index: 1001 !important;
  background: rgba(255, 255, 255, 0.95) !important;
  backdrop-filter: blur(5px) !important;
}

.map-grid-container {
  display: grid;
  grid-template-columns: 40px 1fr 120px; /* 增加图例区域宽度 */
  grid-template-rows: 60px 1fr 30px;
  width: 100%;
  height: 100%;
  gap: 0;
}

.map-title-area {
  grid-column: 1 / -1;
  grid-row: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  position: relative;
}

.map-title-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
}

.map-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
  text-align: center;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.2s ease;
  min-width: 200px;
}

.map-title.editable {
  cursor: pointer;
}

.map-title.editable:hover {
  background: rgba(255, 255, 255, 0.8);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.map-title-input {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  border: 2px solid #007bff;
  border-radius: 6px;
  padding: 8px 16px;
  background: white;
  outline: none;
  min-width: 300px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 123, 255, 0.25);
}

.left-ruler {
  grid-column: 1;
  grid-row: 2;
}

.map-main {
  grid-column: 2;
  grid-row: 2;
  width: 100%;
  height: 100%;
}

.map-legend-area {
  grid-column: 3;
  grid-row: 2;
  border-left: 2px solid #dee2e6;
  padding: 0;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: row;
}

.legend-container {
  position: relative;
  height: 100%;
  width: 80px; /* 增加色带宽度 */
  flex-shrink: 0;
}

.full-height-legend {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  width: 100% !important;
  height: 100% !important;
  margin: 0 !important;
  padding: 0 !important;
  box-sizing: border-box !important;
}

.bottom-ruler {
  grid-column: 2;
  grid-row: 3;
}

/* 经纬度标尺样式 */
.longitude-ruler {
  position: relative;
  display: flex;
  align-items: flex-end;
  min-height: 30px;
}

.latitude-ruler {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  writing-mode: vertical-lr;
  text-orientation: mixed;
  min-width: 40px;
}

.ruler-mark {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
}

.longitude-mark {
  height: 6px;
  width: 1px;
  transform: translateX(-50%);
}

.bottom-ruler .longitude-mark {
  top: 0;
}

.latitude-mark {
  width: 6px;
  height: 1px;
  transform: translateY(-50%);
  right: 0;
}

.ruler-label {
  font-size: 16px;
  color: #495057;
  font-weight: 600;
  white-space: nowrap;
  user-select: none;
}

.longitude-mark .ruler-label {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.bottom-ruler .longitude-mark .ruler-label {
  top: 2px;
}

.latitude-mark .ruler-label {
  position: absolute;
  right: 2px;
  top: 50%;
  transform: translateY(-50%) rotate(180deg);
  writing-mode: vertical-lr;
  text-orientation: mixed;
}

/* 当没有坐标显示时，调整grid布局 */
.map-grid-container.no-coordinates {
  grid-template-columns: 1fr 100px;
  grid-template-rows: 60px 1fr;
}

.map-grid-container.no-coordinates .map-main {
  grid-column: 1;
  grid-row: 2;
  width: 100%;
  height: 100%;
}

.map-grid-container.no-coordinates .map-legend-area {
  grid-column: 2;
  grid-row: 2;
}

/* 地图控件容器 */
.map-controls-container {
  position: absolute;
  top: 60px; /* 标题区域高度 */
  left: 40px; /* 纬度标尺宽度 */
  right: 120px; /* 图例区域宽度 */
  bottom: 30px; /* 经度标尺高度 */
  pointer-events: none; /* 允许地图交互穿透 */
  z-index: 1000;
}

.map-north-arrow {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1001;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 56px;
  height: 56px;
  user-select: none;
  pointer-events: auto; /* 恢复这个元素的交互 */
}

.map-legend {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background: rgba(255, 255, 255, 0.95);
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px);
  min-width: 150px;
  z-index: 1001;
  user-select: none;
  pointer-events: auto; /* 恢复这个元素的交互 */
}

.map-legend h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.legend-items {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 3px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.legend-label {
  font-size: 12px;
  color: #555;
}

.map-scale {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.95);
  padding: 10px 15px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-size: 12px;
  font-weight: 600;
  color: #333;
  z-index: 1001;
  user-select: none;
  pointer-events: auto; /* 恢复这个元素的交互 */
}

.chart-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 400px;
  height: 300px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  z-index: 1001;
  display: flex;
  flex-direction: column;
  pointer-events: auto; /* 恢复这个元素的交互 */
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.chart-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f0f0f0;
  color: #333;
}

#stats-chart {
  flex: 1;
  padding: 10px;
}

:deep(.map-label) {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 11px;
  font-weight: 500;
  color: #333;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

:deep(.leaflet-popup-content-wrapper) {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(5px);
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  padding: 1px;
  /* Fix for layout calculation */
}

:deep(.leaflet-popup-content) {
  margin: 12px 16px;
  font-size: 13px;
  line-height: 1.6;
  min-width: 120px;
}

:deep(.leaflet-popup-content strong) {
  font-weight: 600;
  color: #333;
}

:deep(.leaflet-popup-close-button) {
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
  color: #888;
}

:deep(.leaflet-popup-close-button:hover) {
  background: #f0f0f0;
  color: #333;
}

.legend-title-area {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 5px;
  height: 100%;
  position: relative; /* 为绝对定位的编辑框提供参考 */
  min-width: 40px; /* 确保有足够的最小宽度 */
  overflow: visible; /* 允许编辑框溢出显示 */
}

.legend-title-wrapper {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.legend-title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  writing-mode: vertical-rl;
  text-orientation: mixed;
  padding: 8px 4px;
  border-radius: 4px;
  transition: all 0.2s ease;
  white-space: nowrap;
  letter-spacing: 1px;
  max-width: 40px; /* 限制最大宽度 */
  overflow: hidden;
  text-overflow: ellipsis;
}

.legend-title.editable {
  cursor: pointer;
}

.legend-title.editable:hover {
  background: rgba(0, 0, 0, 0.05);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.legend-title-input {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  border: 2px solid #007bff;
  border-radius: 4px;
  padding: 4px 8px;
  background: white;
  outline: none;
  width: 100px; /* 增加宽度以容纳更多文本 */
  max-width: 100px; /* 限制最大宽度 */
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.25);
  writing-mode: horizontal-tb; /* 输入时保持横向 */
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 1002; /* 确保在最上层 */
}
</style>